import React, { useEffect, useState } from "react";
import {
  Modal,
  Table,
  Pagination,
  Input,
  Form,
  Radio,
  Empty,
  Checkbox,
  Flex,
  Spin,
  Button,
} from "antd";
import {
  getQuestionBankListAction,
  getQuestionBankClassifyListAction,
} from "~/api/questionBankManage";
import { tools } from "@cqsjjb/jjb-common-lib";

export default function ({ onOk, ...props }) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [questionBankList, setQuestionBankList] = useState([]);
  const [questionBankTotal, setQuestionBankTotal] = useState(0);
  const [classifyList, setClassifyList] = useState([]);
  const [selectedClassify, setSelectedClassify] = useState(null);
  const [selectRows, setSelectRows] = useState([]);
  const [confirmLoading, setConfirmLoading] = useState(false);

  // 获取分类列表
  const getClassifyList = () => {
    setLoading(true);
    getQuestionBankClassifyListAction({
      pageIndex: 1,
      pageSize: 100, // 获取足够多的分类
    })
      .then((res) => {
        if (res.classifyList) {
          setClassifyList(res.classifyList);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 获取题库列表
  const getList = (params) => {
    setLoading(true);
    tools
      .routerParamMerge({
        ...tools.routerParamQuery(),
        ...params,
      })
      .then(() => {
        const queryParams = tools.routerParamQuery();
        getQuestionBankListAction(queryParams)
          .then((res) => {
            if (res.questionBankList) {
              setQuestionBankList(res.questionBankList);
              setQuestionBankTotal(res.questionBankTotal || 0);
            }
          })
          .finally(() => {
            setLoading(false);
          });
      });
  };

  // 全选处理
  const allSelect = (checked) => {
    if (checked) {
      setSelectRows(questionBankList);
    } else {
      setSelectRows([]);
    }
  };

  // 分页配置
  const pageObj = {
    total: questionBankTotal,
    showQuickJumper: true,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条数据`,
    sizeSuffix: "条/页",
    current: parseInt(tools.routerParamQuery().pageIndex || 1),
    pageSize: parseInt(tools.routerParamQuery().pageSize || 10),
    onChange: (pageIndex, pageSize) => {
      getList({
        pageIndex,
        pageSize,
      });
      setSelectRows([]);
    },
  };

  // 表格列配置
  const columns = [
    {
      title: "题库编码",
      dataIndex: "id",
      key: "code",
      render: (text) => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <img src="" alt="" style={{ marginRight: "5px" }} />
          {text}
        </div>
      ),
    },
    {
      title: "题库封面",
      dataIndex: "questionBankCoverUrl",
      key: "questionBankCoverUrl",
      render: (text) =>
        text ? (
          <img
            src={text}
            alt="题库封面"
            style={{ width: "50px", height: "50px" }}
          />
        ) : null,
    },
    {
      title: "题库名称",
      dataIndex: "questionBankName",
      key: "questionBankName",
    },
    {
      title: "题库分类",
      dataIndex: "classifyName",
      key: "classifyName",
    },
    {
      title: "岗位",
      dataIndex: "postName",
      key: "postName",
    },
    {
      title: "习题数量",
      dataIndex: "questionNum",
      key: "questionNum",
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      key: "updateTime",
    },
  ];

  useEffect(() => {
    getClassifyList();
    const urlParams = tools.routerParamQuery();
    const classifyId = urlParams.classifyId || null;
    setSelectedClassify(classifyId);
    getList({
      pageIndex: urlParams.pageIndex || 1,
      pageSize: urlParams.pageSize || 10,
      classifyId,
    });
  }, []);

  return (
    <Modal
      title="题库选择器"
      open
      width={1200}
      confirmLoading={confirmLoading}
      onOk={() => {
        console.log(selectRows);
        onOk?.(selectRows);
      }}
      okText="确定"
      cancelText="取消"
      {...props}
    >
      <div className="question-bank-container">
        <div style={{ display: "flex", height: "600px" }}>
          {/* 分类侧边栏 */}
          <div
            style={{
              width: "200px",
              borderRight: "1px solid #f0f0f0",
              padding: "16px",
              overflowY: "auto",
            }}
          >
            <div
              className="category-title"
              style={{
                fontSize: "16px",
                fontWeight: "bold",
                marginBottom: "16px",
              }}
            >
              题库分类
            </div>
            <Radio.Group
              value={selectedClassify}
              onChange={(e) => {
                setSelectedClassify(e.target.value);
                getList({ classifyId: e.target.value, pageIndex: 1 });
              }}
            >
              <Radio
                value={null}
                style={{ display: "block", marginBottom: "8px" }}
              >
                全部
              </Radio>
              {classifyList && classifyList.length > 0 ? (
                classifyList.map((item) => (
                  <Radio
                    key={item.id}
                    value={item.id}
                    style={{ display: "block", marginBottom: "8px" }}
                  >
                    {item.classifyName}
                  </Radio>
                ))
              ) : (
                <Empty
                  description="暂无分类数据"
                  style={{ marginTop: "20px" }}
                />
              )}
            </Radio.Group>
          </div>

          {/* 主内容区域 */}
          <div style={{ flex: 1, padding: "16px", overflowY: "auto" }}>
            <div className="question-bank-table-container">
              <div
                className="category-title"
                style={{
                  fontSize: "16px",
                  fontWeight: "bold",
                  marginBottom: "16px",
                }}
              >
                {selectedClassify
                  ? classifyList.find((item) => item.id === selectedClassify)
                      ?.classifyName
                  : "全部"}
              </div>

              {/* 搜索表单 */}
              <Form
                form={form}
                layout="inline"
                onFinish={(values) => getList(values)}
                style={{ marginBottom: "16px" }}
              >
                <Form.Item name="questionBankName">
                  <Input
                    allowClear
                    placeholder="请输入名称"
                    style={{ width: "200px" }}
                  />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button
                    onClick={() => {
                      form.resetFields();
                      getList({ questionBankName: "" });
                    }}
                  >
                    重置
                  </Button>
                </Form.Item>
              </Form>

              {/* 表格操作栏 */}
              <div className="question-bank-table">
                <div
                  className="all-action-btn"
                  style={{ marginBottom: "16px" }}
                >
                  <div
                    className="left"
                    style={{ display: "flex", alignItems: "center" }}
                  >
                    <Checkbox
                      checked={
                        selectRows.length === questionBankList.length &&
                        questionBankList.length !== 0
                      }
                      onChange={(e) => allSelect(e.target.checked)}
                    >
                      全选
                    </Checkbox>
                    <div style={{ marginLeft: "10px" }}>
                      已勾选 {selectRows.length} 个题库
                    </div>
                  </div>
                </div>

                {/* 表格 */}
                <Spin spinning={loading}>
                  <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={questionBankList}
                    pagination={false}
                    rowSelection={{
                      selectedRowKeys: selectRows.map((item) => item.id),
                      onSelect: (record, selected) => {
                        if (selected) {
                          setSelectRows([...selectRows, record]);
                        } else {
                          setSelectRows(
                            selectRows.filter((item) => item.id !== record.id)
                          );
                        }
                      },
                      onSelectAll: (selected) => {
                        if (selected) {
                          setSelectRows(questionBankList);
                        } else {
                          setSelectRows([]);
                        }
                      },
                    }}
                    scroll={{ y: 400 }}
                  />
                </Spin>

                {/* 分页 */}
                <div
                  style={{
                    display: "flex",
                    padding: "10px 0",
                    justifyContent: "flex-end",
                    marginTop: "16px",
                  }}
                >
                  <Pagination {...pageObj} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
}
